<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-11 10:17:09
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 10:57:55
 * @FilePath: \agriculturec:\Users\21776\Desktop\毕设\shop_app_vue3\pages\classes\components\product-detail.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koroFileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="container">
    <view class="swiper-container">
      <swiper
        v-if="detailImages && detailImages.length > 0"
        class="swiper"
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="1000"
      >
        <swiper-item v-for="(image, index) in detailImages" :key="index">
          <image :src="image" mode="aspectFill" class="slide-image" @error="handleImageError" />
        </swiper-item>
      </swiper>
      <view v-else class="no-image">
        <u-icon name="photo" size="60" color="#ccc"></u-icon>
        <text>暂无图片</text>
      </view>
    </view>
    <u-overlay :show="show" customStyle="z-index: 9999" @click="closeOverlay">
      <view class="overlay-wrap" @click.stop>
        <view class="close-btn" @click="closeOverlay">关闭</view>
        <swiper
          v-if="detailImages.length > 0"
          :current="currentImgIndex"
          indicator-dots
          style="width: 100%; height: 100%"
        >
          <swiper-item
            v-for="(image, idx) in detailImages"
            :key="idx"
            style="display: flex; align-items: center; justify-content: center"
          >
            <image :src="image" style="width: 80%; height: auto" mode="aspectFit" />
          </swiper-item>
        </swiper>
        <view v-else class="no-image-overlay">
          <text>暂无图片</text>
        </view>
      </view>
    </u-overlay>

    <!-- 商品基本信息卡片 -->
    <view class="info-card">
      <view class="price-row">
        <view class="price">
          <text class="symbol">￥</text>
          <text class="amount">{{ productData.discountPrice || productData.price }}</text>
          <text class="original-price" v-if="productData.discountPrice"
            >￥{{ productData.price }}</text
          >
        </view>
        <view class="sales">已售 {{ productData.sales }}+</view>
      </view>

      <view class="title-row">
        <text class="title">{{ productData.name }}</text>
      </view>

      <view class="tags-row">
        <view class="tag unit">{{ productData.specifications }}</view>
        <view class="tag shipping">运费：￥{{ productData.shippingFee }}</view>
        <view class="tag hot" v-if="productData.isHot">热销</view>
        <view class="tag recommend" v-if="productData.isRecommend">推荐</view>
        <view class="tag category">{{ productData.categoryName }}</view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-info-card">
      <view class="section-header">
        <text class="section-title">商品信息</text>
      </view>

      <view class="info-item">
        <text class="info-label">产地</text>
        <text class="info-value">{{ productData.origin }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">保质期</text>
        <text class="info-value">{{ productData.shelfLife }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">储存方式</text>
        <text class="info-value">{{ productData.storageMethod }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">规格</text>
        <text class="info-value">{{ productData.specifications }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">库存</text>
        <text class="info-value">{{ productData.stock }}件</text>
      </view>
    </view>

    <view class="description-card" v-if="productData.description">
      <view class="section-header">
        <text class="section-title">商品描述</text>
      </view>
      <view class="description-content">
        <text class="description-text">{{ productData.description }}</text>
      </view>
    </view>

    <view class="reviews-card">
      <view class="section-header" @click="handleReviews">
        <text class="section-title">用户评价 ({{ reviewStats.totalCount }})</text>
        <view class="more">
          <text class="more-text" v-if="reviewStats.totalCount > 0"
            >好评{{ reviewStats.goodRatePercentage }}%</text
          >
          <u-icon name="arrow-right" size="15" color="#999" />
        </view>
      </view>

      <view class="no-review" v-if="!reviewList || reviewList.length === 0">
        <text>暂无评价</text>
      </view>

      <template v-else>
        <view class="review-item">
          <view class="review-header">
            <u-avatar shape="circle" size="40" :src="reviewList[0].avatar" />
            <view class="review-user">
              <text class="review-username">{{ reviewList[0].userName }}</text>
              <u-rate
                :value="reviewList[0].rating"
                readonly
                size="16"
                active-color="#00b578"
                inactive-color="#b2b2b2"
              ></u-rate>
            </view>
          </view>
          <view class="review-content">
            <text class="review-text">{{ reviewList[0].content }}</text>
          </view>
          <view class="review-images" v-if="reviewList[0].images && reviewList[0].images.length">
            <image
              v-for="(img, index) in reviewList[0].images.slice(0, 3)"
              :key="index"
              :src="img"
              mode="aspectFill"
              class="review-image"
              @click="handleImg(index)"
            ></image>
          </view>
        </view>

        <view class="button-wrapper" v-if="reviewStats.totalCount > 1">
          <u-button @click="handleReviews" class="view-all-button" color="#00b578">
            查看全部{{ reviewStats.totalCount }}条评价
          </u-button>
        </view>
      </template>
    </view>

    <view class="questions-section">
      <view class="section-header">
        <text class="title">问大家</text>
        <text class="more" @click="handleQuestions">查看全部</text>
      </view>
      <view class="loading" v-if="isLoading">
        <uni-load-more status="loading"></uni-load-more>
      </view>

      <view class="empty-state" v-if="!isLoading && (!answerList || answerList.length === 0)">
        <text>暂无问答</text>
      </view>

      <view class="question-list" v-else>
        <view class="question-item">
          <view class="question">
            <text class="q-text">{{ answerList[0].content }}</text>
            <text class="answer-count">{{ answerList[0].answerCount || 0 }}个回答</text>
          </view>
          <text class="time">{{ answerList[0].createTime }}</text>
        </view>
      </view>
    </view>

    <view class="bottom-bar">
      <view class="left-actions">
        <view class="action-item" @click="handleContact">
          <u-icon name="server-man" size="20" color="#00b578" />
          <text>客服</text>
        </view>
        <view class="action-item" @click="handleFavorite">
          <u-icon
            :name="productData.isFavorite ? 'heart-fill' : 'heart'"
            size="20"
            :color="productData.isFavorite ? '#00b578' : '#666'"
          />
          <text>收藏</text>
        </view>
        <view class="action-item" @click="handleCart">
          <u-icon name="shopping-cart" size="20" color="#00b578" />
          <text>购物车</text>
          <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
        </view>
      </view>

      <view class="right-actions">
        <u-button class="action-button add-cart" @click="addToCart">加入购物车</u-button>
        <u-button class="action-button buy-now" @click="buyNow" type="warning">立即购买</u-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useReviewStore } from '../../../store/reviewStore'
import { useProductStore } from '../../../store/productStore'
import { useCartStore } from '../../../store/cartStore'
import { useAnswerStore } from '../../../store/answerStore'
import { storeToRefs } from 'pinia'
import {Favorite} from '../../../api/favorite'

const show = ref(false)
const currentImgIndex = ref(0)

// 初始化 store
const productStore = useProductStore()
const reviewStore = useReviewStore()
const cartStore = useCartStore()
const answerStore = useAnswerStore()
const { currentProduct, loading } = storeToRefs(productStore)
const { stats, reviewList } = storeToRefs(reviewStore)
const { cartList, totalCount } = storeToRefs(cartStore)
const { answerList, isLoading } = storeToRefs(answerStore)

// 商品详情数据
const productData = computed(() => {
  return {
    id: currentProduct.value?.productId,
    name: currentProduct.value?.productName,
    categoryId: currentProduct.value?.categoryId,
    categoryName: currentProduct.value?.categoryName,
    description: currentProduct.value?.description,
    detailImages: currentProduct.value?.detailImages,
    discountPrice: currentProduct.value?.discountPrice,
    imageUrl: currentProduct.value?.mainImage,
    isHot: currentProduct.value?.isHot,
    isRecommend: currentProduct.value?.isRecommend,
    origin: currentProduct.value?.origin,
    price: currentProduct.value?.price,
    sales: currentProduct.value?.sales,
    shelfLife: currentProduct.value?.shelfLife,
    shippingFee: currentProduct.value?.shippingFee,
    specifications: currentProduct.value?.specifications,
    stock: currentProduct.value?.stock,
    storageMethod: currentProduct.value?.storageMethod,
    isFavorite:currentProduct.value?.isFavorite,
  }
})

const reviewStats = computed(() => {
  return {
    averageRating: stats.value?.averageRating ,
    goodCount: stats.value?.goodCount ,
    goodRatePercentage: stats.value?.goodRatePercentage ,
    imageCount: stats.value?.imageCount ,
    qualityCount: stats.value?.qualityCount ,
    starRating: stats.value?.starRating ,
    totalCount: stats.value?.totalCount ,
  }
})


const detailImages = computed(() => productStore.getDetailImages)

const handleImg = (index) => {
  currentImgIndex.value = index
  show.value = true
}

const closeOverlay = () => {
  show.value = false
}

const handleContact = () => {
  uni.navigateTo({
    url: '/pages/message/components/chat',
  })
}

const handleFavorite = () => {
  const res=Favorite(currentProduct.value.productId)
  if(res.code===200){
    productData.isFavorite=res.data
  }
}

const handleCart = () => {
  uni.switchTab({
    url: '/pages/car/index',
  })
}

const addToCart = async () => {
  try {
    if (!currentProduct.value || !currentProduct.value.productId) {
      uni.showToast({
        title: '商品信息不完整',
        icon: 'none',
      })
      return
    }

    const cartDTO = {
      fruitId: currentProduct.value.productId,
      quantity: 1,
      selected: 1,
    }

    const res = await cartStore.addItemToCart(cartDTO)

    if (res.code === 200) {
      uni.showToast({
        title: '加入购物车成功',
        icon: 'success',
      })
      await cartStore.updateCartInfo()
    }
  } catch (error) {
    uni.showToast({
      title: '加入购物车失败',
      icon: 'none',
    })
  }
}

const buyNow = () => {
  if (!currentProduct.value?.productId) {
    uni.showToast({
      title: '商品信息不完整',
      icon: 'none',
    })
    return
  }

  // 准备订单信息
  const orderInfo = {
    items: [
      {
        id: currentProduct.value.productId,
        name: currentProduct.value.productName,
        price: currentProduct.value.price,
        image: currentProduct.value.mainImage,
        quantity: 1,
        unit: currentProduct.value.unit,
      },
    ],
    totalAmount: currentProduct.value.price,
  }

  // 将订单信息存储到本地
  uni.setStorageSync('orderInfo', JSON.stringify(orderInfo));

  // 直接跳转到结算页面
  uni.navigateTo({
    url: '/components/Settlement',
  })
}

const handleReviews = () => {
  const productId = currentProduct.value?.productId || currentProduct.value?.id
  if (!productId) {
    uni.showToast({
      title: '商品信息不完整',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: `/components/userReviews?fruitId=${productId}`,
  })
}

const handleQuestions = () => {
  uni.navigateTo({
    url: `/components/userQuestions?productId=${currentProduct.value?.productId}`,
  })
}

const handleImageError = (e) => {
  try {
    const index = e.detail?.index
    if (
      index !== undefined &&
      Array.isArray(detailImages.value) &&
      index >= 0 &&
      index < detailImages.value.length
    ) {
      const newImages = [...detailImages.value]
      newImages[index] = '/static/default-product.png'
      if (index === 0) {
        currentProduct.value.mainImage = '/static/default-product.png'
      } else if (Array.isArray(currentProduct.value.detailImages)) {
        currentProduct.value.detailImages[index - 1] = '/static/default-product.png'
      }
    }
  } catch (err) {
  }
}

onLoad(async (options) => {
  const detailId = Number(options.detailId)
  if (!detailId) {
    uni.showToast({
      title: '商品ID不能为空',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }

  try {
    await productStore.loadProductDetail(detailId)
    const productId = currentProduct.value?.productId || currentProduct.value?.id
    if (productId) {
      await reviewStore.loadReviewStats(productId)
      await reviewStore.loadReviewList(productId, 0)
      await answerStore.loadAnswerList(productId)
    } else {
      uni.showToast({
        title: '获取商品信息失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '加载数据失败',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})

onUnmounted(() => {
  if (productStore) {
    productStore.clearCurrentProduct()
  }
  if (reviewStore) {
    reviewStore.resetReviewData()
  }
})
</script>

<style scoped lang="scss">
@import '@/styles/mixins.scss';
@import '@/styles/variables.scss';

.container {
  min-height: 100vh;
  padding-bottom: 120rpx;
  background-color: $bg-color;
}

// 轮播图样式
.swiper-container {
  width: 100%;
  overflow: hidden;
}

.swiper {
  width: 100%;
  height: 750rpx;

  .slide-image {
    width: 100%;
    height: 100%;
  }
}

.no-image {
  width: 100%;
  height: 750rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;

  text {
    margin-top: 20rpx;
    color: #999;
    font-size: 28rpx;
  }
}

.no-image-overlay {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
}

// 图片预览遮罩层
.overlay-wrap {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn {
  position: absolute;
  top: 40rpx;
  right: 40rpx;
  color: #fff;
  font-size: 28rpx;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  z-index: 10000;
}

// 商品基本信息卡片
.info-card {
  margin: 0;
  padding: 30rpx;
  background-color: $bg-color-white;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.price {
  display: flex;
  align-items: baseline;

  .symbol {
    font-size: 28rpx;
    color: #ff8800;
    margin-right: 4rpx;
  }

  .amount {
    font-size: 48rpx;
    font-weight: bold;
    color: #ff8800;
  }
}

.sales {
  font-size: 24rpx;
  color: $text-color-light;
}

.title-row {
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: $text-color;
    line-height: 1.4;
  }
}

.tags-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;

  .tag {
    font-size: 24rpx;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;

    &.unit {
      background-color: $bg-color-light;
      color: $text-color;
    }

    &.hot {
      background-color: rgba($primary-color, 0.1);
      color: $primary-color;
    }

    &.recommend {
      background-color: rgba($secondary-color, 0.1);
      color: $secondary-color;
    }

    &.category {
      background-color: rgba($warning-color, 0.1);
      color: $warning-color;
    }
  }
}

// 商品信息
.product-info-card {
  margin: 20rpx 0 0;
  padding: 30rpx;
  background-color: $bg-color-white;
}

.info-item {
  display: flex;
  padding: 15rpx 0;
  border-bottom: 1px solid $border-color;

  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  width: 140rpx;
  font-size: 26rpx;
  color: $text-color-secondary;
}

.info-value {
  flex: 1;
  font-size: 26rpx;
  color: $text-color;
}

// 商品描述
.description-card {
  margin: 20rpx 0 0;
  padding: 30rpx;
  background-color: $bg-color-white;

  .description-content {
    padding: 20rpx 0;

    .description-text {
      font-size: 28rpx;
      color: $text-color;
      line-height: 1.6;
    }
  }
}

// 用户评价
.reviews-card {
  margin: 20rpx 0 0;
  padding: 30rpx;
  background-color: $bg-color-white;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: $text-color;
  }

  .more {
    display: flex;
    align-items: center;

    .more-text {
      font-size: 26rpx;
      color: $text-color-secondary;
      margin-right: 6rpx;
    }
  }
}

.no-review {
  padding: 60rpx 0;
  text-align: center;
  color: $text-color-light;
  font-size: 28rpx;
}

.review-item {
  padding: 20rpx 0;
  border-bottom: 1px solid $border-color;

  &:last-child {
    border-bottom: none;
  }
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.review-user {
  margin-left: 12rpx;

  .review-username {
    font-size: 28rpx;
    color: $text-color;
    font-weight: bold;
    margin-bottom: 4rpx;
  }
}

.review-content {
  margin-bottom: 16rpx;

  .review-text {
    font-size: 28rpx;
    color: $text-color;
    line-height: 1.5;
  }
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 16rpx;

  .review-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    object-fit: cover;
  }
}

.button-wrapper {
  margin-top: 20rpx;
  display: flex;
  justify-content: center;

  .view-all-button {
    width: 80% !important;
    border-radius: 40rpx !important;
    background-color: #00b578 !important;
  }
}

// 问答模块
.questions-section {
  margin: 20rpx 0 0;
  padding: 30rpx;
  background-color: $bg-color-white;
  border-radius: 12rpx;
}

.question-list {
  .question-item {
    padding: 20rpx 0;
    border-bottom: 1px solid $border-color;

    &:last-child {
      border-bottom: none;
    }
  }
}

.question {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10rpx;

  .q-text {
    flex: 1;
    font-size: 28rpx;
    color: $text-color;
    line-height: 1.5;
  }

  .answer-count {
    font-size: 24rpx;
    color: $text-color-secondary;
    margin-left: 20rpx;
  }
}

.time {
  font-size: 24rpx;
  color: $text-color-secondary;
}

.loading {
  padding: 40rpx 0;
  text-align: center;

  text {
    color: $text-color-light;
    font-size: 28rpx;
  }
}

.empty-state {
  padding: 60rpx 0;
  text-align: center;
  color: $text-color-light;
  font-size: 28rpx;
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: $bg-color-white;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.left-actions {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 40rpx;

  u-icon {
    color: #00b578;
  }
}

.action-item text {
  font-size: 22rpx;
  color: $text-color-secondary;
  margin-top: 6rpx;
}

.right-actions {
  flex: 1;
  display: flex;
  gap: 20rpx;
}

.action-button {
  flex: 1;
  height: 80rpx !important;
  border-radius: 40rpx !important;

  &.add-cart {
    background-color: #07c160 !important;
    color: $bg-color-white !important;
  }
}

.cart-badge {
  position: absolute;
  top: -6rpx;
  right: -6rpx;
  background-color: #00b578;
  color: $bg-color-white;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6rpx;
}

.original-price {
  font-size: 24rpx;
  color: $text-color-light;
  text-decoration: line-through;
  margin-left: 12rpx;
}

.shipping {
  background-color: #f5f5f5;
  color: #666;
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.info-card {
  .price-row {
    .price {
      display: flex;
      align-items: baseline;

      .symbol {
        font-size: 28rpx;
        color: #ff8800;
      }

      .amount {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff8800;
      }
    }
  }
}

.product-info-card {
  .info-item {
    padding: 20rpx 0;
    display: flex;
    border-bottom: 1rpx solid $border-color;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 140rpx;
      color: $text-color-secondary;
      font-size: 28rpx;
    }

    .info-value {
      flex: 1;
      color: $text-color;
      font-size: 28rpx;
    }
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: $text-color;
}
</style>
